import axios from "axios";
import { ElMessage } from "element-plus";
// const BASE_URL = process.env.VUE_APP_BASE_URL

// create an axios instance
const service = axios.create({
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30 * 1000 // request timeout
});

// request interceptors
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    // 设置baseURL
    // config.baseURL = config.url.startsWith('/mock') ? '' : BASE_URL
    if (localStorage.getItem("ticktoken") && !config.url.includes("/nwzk")) {
      config.headers["Access-Token"] = localStorage.getItem("ticktoken");
    }
    return config;
  },
  (error) => {
    // do something with request error
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    if (response.status == 200 && response.data.errorMessage == null) {
      return response.data;
    } else {
      handleErrorData(response.data);
    }
  },
  (error) => {
    console.log("响应报错===>", error);
    // 非取消请求
    if (!axios.isCancel(error)) {
      // 401无权限判断
      if (error.response && error.response.status === 401) {
        return Promise.reject("没有接口权限，请联系管理员");
      } else if (error.response && error.response.status === 531) {
        setTimeout(() => {
          // 清除登录状态
          localStorage.clear();
          window.location.href = "/";
        }, 1000);
        return Promise.reject("登录超时，请重新登录");
      }
    }
    if (!error.message) {
      ElMessage.error(error.message || "未知错误");
    }
    return Promise.reject(error);
  }
);
//对错误信息的处理函数
function handleErrorData(errMes) {
  // console.log('error', errMes);
  if (errMes.errorMessage) {
    ElMessage.error(errMes.errorMessage);
  } else {
    switch (errMes.code) {
      case 401:
        ElMessage.error("未授权，请重新登录!");
        break;
      case 403:
        ElMessage.error("拒绝访问");
        break;
      case 404:
        ElMessage.error("很抱歉，资源未找到!");
        break;
      case 500:
        ElMessage.error("服务器错误!");
        break;
      case 504:
        ElMessage.error("网络超时!");
        break;
      default:
        ElMessage.error("服务正在联调中，请稍后!");
        break;
    }
  }
}
export default service;
